package com.easemob.helpdesk.activity.chat;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.MediaController;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Toast;
import android.widget.VideoView;

import com.easemob.helpdesk.activity.BaseActivityV2;
import com.easemob.helpdesk.activity.ChatActivity;
import com.easemob.helpdesk.activity.ContextMenu;
import com.easemob.helpdesk.bean.MsgChat;
import com.easemob.helpdesk.utils.DownloadManager;
import com.housekeeperapp.R;
import com.hyphenate.kefusdk.utils.HDLog;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Request;

/**
 * Created by wsj on 2018/6/7.
 */

public class MsgShowVideoActivity extends BaseActivityV2 {

    private RelativeLayout loadingLayout;
    private ProgressBar progressBar;
    private VideoView videoView;
    private RelativeLayout video_view_layout;
    private String localFilePath;
    private MsgChat message;
    private String msgid;
    private String remoteurl;

    public static final int REQUEST_CODE_CONTEXT_MENU = 0x011;
    public static final int RES_CODE_SAVE = 0x022;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.hd_showvideo_activity);

        loadingLayout = (RelativeLayout) findViewById(R.id.loading_layout);
        progressBar = (ProgressBar) findViewById(R.id.progressBar);
        videoView = (VideoView)this.findViewById(R.id.video_view);
        video_view_layout = (RelativeLayout) this.findViewById(R.id.video_view_layout);


        remoteurl = getIntent().getStringExtra("remoteurl");
        msgid = getIntent().getStringExtra("msgid");

        localFilePath = DownloadManager.getResourcePath(msgid);

//        String remotepath = getIntent().getStringExtra("remotepath");
//        String secret = getIntent().getStringExtra("secret");
//        message = getIntent().getParcelableExtra("videomsg");

        if (localFilePath != null && new File(localFilePath).exists()) {

//            Intent intent = new Intent(Intent.ACTION_VIEW);
//            intent.setDataAndType(Uri.fromFile(new File(localFilePath)),
//                    "video/mp4");
//            startActivity(intent);
//            finish();
            loadingLayout.setVisibility(View.GONE);
            showLocalVideo(localFilePath);

        } else {
//            HDLog.d(TAG, "download remote video file");
            Map<String, String> maps = new HashMap<String, String>();
//            if (!TextUtils.isEmpty(secret)) {
//                maps.put("share-secret", secret);
//            }
            downloadVideo();
        }

        videoView.setZOrderOnTop(true);
        video_view_layout.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                Intent intent = new Intent(MsgShowVideoActivity.this, ContextMenu.class);
                intent.putExtra("type", ContextMenu.TYPE_CONTEXT_MENU_VIDEO);

                startActivityForResult(intent, REQUEST_CODE_CONTEXT_MENU);
                return true;
            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_CONTEXT_MENU) {
            if (resultCode == RES_CODE_SAVE) {
                Toast.makeText(this, "已成功保存到"+DownloadManager.getSDPATH(), Toast.LENGTH_LONG).show();
            }
        }

    }

    /**
     * 播放本地视频
     *
     * @param localPath 视频路径
     */
    private void showLocalVideo(String localPath) {
//        loadingLayout.setVisibility(View.GONE);
        video_view_layout.setVisibility(View.VISIBLE);

//        Intent intent = new Intent(Intent.ACTION_VIEW);
//        intent.setDataAndType(Uri.fromFile(new File(localPath)),
//                "video/mp4");
//        startActivity(intent);
//        finish();

        videoView.setMediaController(new MediaController(this));
        videoView.setVideoURI(Uri.fromFile(new File(localPath)));
        videoView.requestFocus();
        videoView.start();
    }

    /**
     * 下载视频文件
     */
    private void downloadVideo() {

//        if (TextUtils.isEmpty(localFilePath)) {
//            localFilePath = getLocalFilePath(remoteUrl);
//        }
//        if (new File(localFilePath).exists()) {
//            showLocalVideo(localFilePath);
//            return;
//        }

        loadingLayout.setVisibility(View.VISIBLE);

        DownloadManager.downloadFile(remoteurl, msgid, new DownloadManager.ResultCallback() {
            @Override
            public void onError(Request request, Exception e) {
                File file = new File(localFilePath);
                if (file.exists()) {
                    file.delete();
                }
            }

            @Override
            public void onResponse(Object response) {
                runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        loadingLayout.setVisibility(View.GONE);
                        progressBar.setProgress(0);
                        localFilePath = DownloadManager.getResourcePath(msgid);

                        showLocalVideo(localFilePath);
                    }
                });
            }

            @Override
            public void onProgress(double total, final double current) {
                runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        progressBar.setProgress((int)current);
                    }
                });
            }
        });

//        message.setMessageCallback(new HDDataCallBack() {
//            @Override
//            public void onSuccess(Object o) {
//                runOnUiThread(new Runnable() {
//
//                    @Override
//                    public void run() {
//                        loadingLayout.setVisibility(View.GONE);
//                        progressBar.setProgress(0);
//                        showLocalVideo(localFilePath);
//                    }
//                });
//            }
//
//            @Override
//            public void onProgress(final int progress) {
//                HDLog.d("ease", "video progress:" + progress);
//                runOnUiThread(new Runnable() {
//
//                    @Override
//                    public void run() {
//                        progressBar.setProgress(progress);
//                    }
//                });
//
//            }
//
//            @Override
//            public void onError(int error, String msg) {
//                HDLog.e("###", "offline file transfer error:" + msg);
//                File file = new File(localFilePath);
//                if (file.exists()) {
//                    file.delete();
//                }
//            }
//        });
//        HDClient.getInstance().chatManager().downloadAttachment(message);
    }

    @Override
    public void onBackPressed() {
        finish();
    }
}
